package io.jee.runshan.utils;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;

public class PropertiesUtils {
	private static final String DEFAULT_PROPERTIES_FILE = "config.properties";
	private static Properties properties = null;
	private static long lastmodify = 0L;

	private static void loadProperties() {
		try {
			ClassPathResource cr = new ClassPathResource(DEFAULT_PROPERTIES_FILE);
			File file = cr.getFile();
			if (lastmodify != file.lastModified()) {
				InputStream is = cr.getInputStream();
				properties = new Properties();
				properties.load(new InputStreamReader(is, "UTF-8"));
			}
		} catch (Exception e) {
			throw new RuntimeException("Failed to get properties!");
		}
	}
	
	public static Properties loadProperties(String propertiesFile) {
		Properties properties = null;
		try {
			ClassPathResource cr = new ClassPathResource(propertiesFile);
			File file = cr.getFile();
			if (lastmodify != file.lastModified()) {
				InputStream is = cr.getInputStream();
				properties = new Properties();
				properties.load(new InputStreamReader(is, "UTF-8"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return properties;
	}
	
	public static Map<String, String> toMap (Properties properties) {
		if (properties == null || properties.isEmpty()) {
			return null;
		}
		Map<String, String> result = new HashMap<String, String>();
		for (String name : properties.stringPropertyNames()) {
			result.put(name, properties.getProperty(name));
		}
		return result;
	}
	

	public static String getValue(String key) {
		loadProperties();
		return properties.getProperty(key);
	}

}
